package com.cmict.data.form.api.util;

import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 下载的帮助类
 *
 * @author: qiaoyu
 * @date: 2022-09-21
 */
public class CompressUtil{

  /*public static void main(String[] args) throws Exception {
      TrustManager[] trustAllCerts = {new TrustAllManager()};
      SSLContext sc = null;
      sc = SSLContext.getInstance("TLS");
      sc.init(null, trustAllCerts, new java.security.SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      HostnameVerifier allHostsValid = new HostnameVerifier() {
          public boolean verify(String hostname, SSLSession session) {
              return true;
          }
      };
      HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
      URL url = new URL("https://192.168.108.81:9000/awesome-bucket/a7854fce38960ac4e0e57987f84d381f.png");
      HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
      try (InputStream is = connection.getInputStream();
           ) {
          byte[] b = new byte[1024];
          while ((is.read(b)) != -1) {
          }
      } catch (Exception e) {
          e.printStackTrace();
      }
    }*/

    /**
     * 生成zip压缩文件
     * @param filePaths
     * @param zipFilePath
     * @param keepDirStructure
     */
    public static void compress(List<Map<String, String>> filePaths, String zipFilePath, Boolean keepDirStructure,String uploadFolder) {
        //uploadFolder = "E:\\file\\";
        createFile(uploadFolder);
        byte[] buf = new byte[1024];
        File zipFile = new File(zipFilePath);
        try {
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
            for (int i = 0; i < filePaths.size(); i++) {
                String relativePath = filePaths.get(i).get("filePath");
                String relativeName = filePaths.get(i).get("fileName");
                if (StringUtils.isEmpty(relativePath)) {
                    continue;
                }
                TrustManager[] trustAllCerts = {new TrustAllManager()};
                SSLContext sc = null;
                sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                HostnameVerifier allHostsValid = new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                };
                HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
                URL url = new URL(relativePath);
                HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
                try{
                    InputStream is = connection.getInputStream();
                    FileOutputStream fos = new FileOutputStream(uploadFolder+relativeName);
                    byte[] b = new byte[1024];
                    // 读取到的数据长度
                    int len;
                    // 开始读取
                    while ((len = is.read(b)) != -1) {
                        fos.write(b, 0, len);
                    }
                    fos.close();
                    is.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
                File sourceFile = new File(uploadFolder+relativeName);
                if (sourceFile == null || !sourceFile.exists()) {
                    continue;
                }
                FileInputStream fis = new FileInputStream(sourceFile);
                if (keepDirStructure != null && keepDirStructure) {
                    zos.putNextEntry(new ZipEntry(relativePath));
                } else {
                    zos.putNextEntry(new ZipEntry(String.valueOf(new ZipEntry(i + "_" + relativeName))));
                }
                int len;
                while ((len = fis.read(buf)) > 0) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                // zos.close();
            }
            zos.close();
            if (!zipFile.exists()) {
                zipFile.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 判断文件是否存在，不存在就创建
     * @param filePath
     */
    public static void createFile(String filePath) {
        try {
            File dir = new File(filePath);
            if(!dir.exists()){
                dir.mkdirs();//创建目录
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载zip
     *
     * @param response
     * @param zipName  浏览器header中zip名称
     * @param zipFile  zipFile文件
     */
    public static void downloadZip(HttpServletResponse response, String zipName, File zipFile) {
        //下载文件
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/zip");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipName, "UTF-8"));
            ServletOutputStream out = response.getOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            FileInputStream fis = new FileInputStream(zipFile);
            while ((len = fis.read(buffer)) > 0) {
                out.write(buffer, 0, len);
                out.flush();
            }
            out.close();
            fis.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
      /*  //下载文件
        try {
            // path是指想要下载的文件的路径
            File file = zipFile;
// 获取文件名
            String filename = zipName;
// 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
// 清空response
            response.reset();
// 设置response的Header
            response.setCharacterEncoding("UTF-8");
//Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
//attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
// filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
// 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }*/
    }

    private static class TrustAllManager
            implements X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkServerTrusted(X509Certificate[] certs,
                                       String authType) {
        }

        public void checkClientTrusted(X509Certificate[] certs,
                                       String authType) {
        }
    }
    /*public static void main(String[] args) throws IOException, NoSuchAlgorithmException, KeyManagementException {

        TrustManager[] trustAllCerts = {new TrustAllManager()};
        SSLContext sc = null;
        sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        URL url = new URL("https://192.168.108.81:9000/awesome-bucket/780723eca1d2e5e640aaa9db87830608.png");
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        String filename = "E:\\file\\q1.png";  //下载路径及下载图片名称
        File file = new File(filename);
        FileOutputStream os = new FileOutputStream(file);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        //System.out.println(i);
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }*/
}

